<?php


namespace App\Listeners;


use App\Events\OrderPaySuccess;
use App\Models\Group;
use App\Models\User;
use App\Models\UserBill;
use App\Services\BalanceService;
use App\Services\OrderService;

class OrderPaySuccessUpdateListener
{
    public $order;
    public $payType;
    public $attach;

    /**
     * Handle the event.
     *
     * @param  OrderPaySuccess $event
     * @return void
     * @throws \Throwable
     */
    public function handle(OrderPaySuccess $event)
    {
        $this->order = $event->order;
        $this->attach = $event->attach;
        $this->payType = $event->payType;

        switch ($this->attach) {
            case 'legwork':
                //购买商品
                $this->doLegwork();
                $this->log();
                break;
            case 'recharge_balance':
                //余额充值
                BalanceService::rechargeBalanceSuccessNotify($this->order);
                break;
            case 'ticket':
                //神马购买票
                $this->doTicket();
                break;

        }
    }

    /**
     * 瓜瓜配送更新字段
     */
    private function doLegwork()
    {
        //如果是第三方下单
        if(!$this->order->out_trade_no){
            $group = Group::whereAppId($this->order->uid)->first();
            if($group && $group->times != -1){
                $group->times -= 1;
                $group->save();
            }
        }
    }

    /**
     * 把买票的钱放到999账户身上
     */
    private function doTicket()
    {
        $user = User::find(999);
        $present = $user->balance;
        $user->balance = bcadd($this->order->pay_price, $user->balance,2) ;
        $user->save();

        $buyer = User::find($this->order->uid);

        //给用户加log
        BalanceService::addCreditLog(24, $this->order->uid, 1, -$this->order->pay_price, $buyer->balance , "购买神马配送票", 0, 0, 0, 0, $this->order->id);
        //给999加log
        BalanceService::addCreditLog(24, $user->id, 1, $this->order->pay_price, $present, "用户".$this->order->uid."购买神马配送票", 0, 0, 0, 0, $this->order->id);
    }

    /**
     * 记录支付日志
     */
    public function log()
    {
        if(!$this->order->out_trade_no){
            $order = $this->order;
            $mark = '微信支付' . $order->pay_price . '购买商品';
            //订单变化日志
            OrderService::log($order->id, 'pay_success', '用户付款成功');
            //账单
            UserBill::expend('购买商品', $order->uid, 'now_money', 'pay_goods', $order->pay_price, $order->id, 0, $mark, 1);
        }
    }
}
